package com.zut.domain.sevice.impl;
import com.google.gson.Gson;
import com.google.gson.internal.$Gson$Types;
import com.google.gson.reflect.TypeToken;
import com.zut.auth.infra.entity.AuthPermission;
import com.zut.auth.infra.service.AuthPermissionService;
import com.zut.common.enums.IsDeletedFlagEnum;
import com.zut.common.enums.StatusFlagEnum;
import com.zut.domain.convert.AuthPermissionBOConverter;
import com.zut.domain.entity.AuthPermissionBO;
import com.zut.domain.redis.RedisUtil;
import com.zut.domain.sevice.AuthPermissionDomainService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AuthPermissionDomainServiceImpl implements AuthPermissionDomainService {


    @Resource
    private AuthPermissionService authPermissionService;

    @Resource
    private RedisUtil redisUtil;

    private static String authPermissionPrefix="auth.permission";

    //添加权限
    @SneakyThrows
    @Override
    public Boolean add(AuthPermissionBO authPermissionBO) {
        AuthPermission authPermission= AuthPermissionBOConverter.INSTANCE.ConvertBOTo(authPermissionBO);
        authPermission.setIsDelete(IsDeletedFlagEnum.UN_DELETED.getCode());
        authPermission.setStatus(StatusFlagEnum.ENABLE.getCode());
        int insert = authPermissionService.insert(authPermission);
        return insert>0;
    }

    //更改角色信息
    @Override
    public Boolean update(AuthPermissionBO authPermissionBO) {
        AuthPermission authPermission= AuthPermissionBOConverter.INSTANCE.ConvertBOTo(authPermissionBO);
        int update = authPermissionService.update(authPermission);
        return update>0;
    }

    //删除角色
    @Override
    public Boolean delete(AuthPermissionBO authPermissionBO) {
        AuthPermission authPermission= AuthPermissionBOConverter.INSTANCE.ConvertBOTo(authPermissionBO);
        authPermission.setIsDelete(IsDeletedFlagEnum.DELETED.getCode());
        int update = authPermissionService.update(authPermission);
        return update>0;
    }


    //获取用户权限
    @Override
    public List<String> getPermission(String userName) {
        String key = redisUtil.buildKey(authPermissionPrefix, userName);
        String value = redisUtil.get(key);
        List<AuthPermission> authList = new Gson().fromJson(value, new TypeToken<List<AuthPermission>>(){
        }.getType());
        List<String> permissionList = authList.stream().map(AuthPermission::getPermissionKey).collect(Collectors.toList());
        return permissionList;
    }


}
